package home;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Random;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
import javax.swing.border.EtchedBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Brokerage extends JFrame implements ActionListener,
		ListSelectionListener {


	private static final long serialVersionUID = 1L;

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) {
		Brokerage runnable = new Brokerage();
		runnable.init();

	}

	/**
	 * Instance variables.  I needed lots of them because of the nature of this event-driven program.  Because
	 * of the nature of the program I needed my actionPerformed methods to have access to all of the program
	 */
	private JTextArea accountInstructions;
	private Vector<Account> accountList = new Vector<Account>();
	private File accountsFile;
	private JComboBox allDaysBox;
	private Vector<String> allStockHistory = new Vector<String>();
	private Vector<Transaction> allTransactionsList = new Vector<Transaction>();
	private JTextField balance;
	private JPanel buyPanel;
	private Calendar cal;
	private JComboBox<Account> chooseAccount;
	private boolean clearTable = false;
	private JPanel createAccountPanel;
	private JTextArea currentBalanceText;
	private JTextArea currentCashValue;
	private JPanel currentPortfolioPanel;
	private JTable currentPortfolioTable;
	private JTextArea currentStockValue;
	private JPanel customerPanel = new JPanel();
	private JTextField date;
	private JPanel dayPortfolioPanel = new JPanel();
	private JTextField depositAmount;
	private JPanel depositPanel;
	private JTextArea displaySelectedStock;
	private JTextArea displaySelectedStock2;
	private JTextArea enterBalance;
	private JTextArea enterDate;
	private int feeRevenue = 0;
	private JTextArea filler;
	int height;
	private JTextField howManyShares;
	private JTextField howManyShares2;
	private BufferedReader in;
	private JTextArea instructions;
	private ListSelectionModel listSelectionModel;
	private ListSelectionModel listSelectionModel2;
	private JPanel mainPage = new JPanel();
	private boolean mainPageCached = false;
	private JTextField name;
	private JTextArea nameInstruction;
	private JMenuItem newAcct;
	private Boolean once = false;
	private BufferedWriter out;
	private JMenuItem save;
	private JMenuItem saveAs;
	private JMenuItem feesByDayButton;
	private File savedFile;
	private Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
	private JScrollPane scrollpane;
	private Account selectedAccount;
	private JTextArea selectedAccountInfo;
	private String selectedStock;
	private String selectedStock2;
	private JPanel sellPanel;
	private Vector<Stock> stockList = new Vector<Stock>();
	private String stockToSell;
	private JButton submitAccount;
	private int today;
	private File transactionsFile;
	private JPanel feesByDayPanel;
	private int width = screenSize.width;
	private JPanel feesByDayPanel2;
	private JComboBox allDaysBox2;
	private JTextArea displayFeesByDay;
	private Boolean feesByDayIsOpen = false;

	
	/**
	 * Initialization of the program.  Displays the welcome message, sets the height and width of the
	 * primary JFrame, calls the InitMenu() in order to initialize the menu, sets the Stock interval, loads all of the stocks
	 * from their last known price, and then displays the Choose Account panel.
	 */
	public void init() {
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setLayout(new FlowLayout());

		// make the frame half the height and width
		Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
		int height = screenSize.height;
		int width = screenSize.width;
		this.setSize(width / 2, height / 2);

		// center frame
		this.setLocationRelativeTo(null);

		// introduction w/icon
		JOptionPane introduction = new JOptionPane();
		ImageIcon myIcon = new ImageIcon("brokerIcon.jpg");
		JOptionPane
				.showMessageDialog(
						this.getComponent(0),
						"Welcome To MET-Broker v1.0.  Click OK to Proceed to Application.",
						"Welcome!", 0, myIcon);
		introduction.setIcon(myIcon);
		// Set the date of beginning of brokerage firm to January 1st, 2013
		cal = Calendar.getInstance();
		today = cal.get(Calendar.DAY_OF_YEAR);
		System.out.println("DAY OF YEAR: " + today);
		loadStocks(); //Loads all stocks at their most recently known price 
		initMenu();  //Initializes the JMenuBar
		stockChangeInterval(); //Sets the automatic stock change interval
		chooseAccount(); //Displays the Choose Account page.
		this.setVisible(true);

	}
	
	/**
	 * Loads StockQuotes.txt file, which includes the stocks at their most recently known price.  The most recently known price is the price of the stocks
	 * the last time the METBroker program was opened.
	 *
	 */
	public void loadStocks() {
		BufferedReader reader;
		String singleStock;
		try {
			reader = new BufferedReader(new FileReader("StockQuotes.txt"));
			singleStock = null;
			stockList.clear();

			while ((singleStock = reader.readLine()) != null) {
				Stock tempStock = new Stock();
				tempStock.setStockSymbol((singleStock.split(",")[0]));
				tempStock.setStockPrice((Double.parseDouble(singleStock
						.split(",")[1])));
				stockList.add(tempStock);

			}
			reader.close();

		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}

	}

	/**
	 * Initializes the MenuBar and adds the correct Menu Items.  
	 */
	public void initMenu() {
		JMenuBar bar = new JMenuBar();
		JMenu menu = new JMenu("File");
		save = new JMenuItem("Save");
		newAcct = new JMenuItem("Create New Account");
		saveAs = new JMenuItem("Save As");
		feesByDayButton = new JMenuItem("View Fee Revenue By Day");
		newAcct.addActionListener(this);
	
		if (accountList.size() == 0) { //Disables certain features until an Accounts text file is loaded.
			newAcct.setEnabled(false);
			saveAs.setEnabled(false);
			save.setEnabled(false);
			feesByDayButton.setEnabled(false);
		}
		JMenuItem quit = new JMenuItem("Quit");
		JMenuItem loadAccounts = new JMenuItem("Load Accounts");
		feesByDayButton.addActionListener(this);
		quit.addActionListener(this);
		save.addActionListener(this);
		saveAs.addActionListener(this);
		loadAccounts.addActionListener(this);
		menu.add(loadAccounts);
		menu.add(save);
		menu.add(saveAs);
		menu.add(newAcct);
		menu.add(feesByDayButton);
		menu.add(quit);
		bar.add(menu);
		this.setJMenuBar(bar);
	}
	
	
	/**
	 * This function takes care of the change in stock value.  Every 15 seconds, the stocks are read into a list, and each stock
	 * is then incremented by a random amount and written back into the StockQuotes.txt file.  
	 */
	public void stockChangeInterval() {

		int delay = 15000; // Stocks change at an interval of every 15,000 ms
		ActionListener stockChanger = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent evt) {
				Random random = new Random();
				for (int x = 0; x <= stockList.size() - 1; x++) {
					stockList.get(x).setStockPrice(
							stockList.get(x).getStockPrice()
									+ random.nextDouble());
				}

				BufferedWriter out3 = null;

				try {
					out3 = new BufferedWriter(new FileWriter("StockQuotes.txt"));
					for (int x = 0; x <= stockList.size() - 1; x++) {
						if (x > 0) {
							out3.newLine();
						}
						out3.write(stockList.get(x).getStockSymbol() + ","
								+ stockList.get(x).getStockPrice());
					}
					out3.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					System.out.println(e1.getMessage());
				}
			}
		};
		new Timer(delay, stockChanger).start();

		// Save new stocks to stocks file

	}

	/**
	 * Displays the accounts loaded from the Accounts.txt file and allows user to select an account and then access the account.
	 */
	public void chooseAccount() {
		// Create GUI
		mainPage.setLayout(new GridLayout(3, 1));
		mainPage.setPreferredSize(new Dimension(this.getWidth() / 2, this
				.getHeight() / 2));
		mainPage.setBorder(BorderFactory.createEtchedBorder(
				EtchedBorder.RAISED, Color.white, Color.black));

		accountInstructions = new JTextArea(
				"\nLoad user accounts by pressing File --> Load Accounts.  \nThen select an account to access.");

		accountInstructions.setEditable(false);
		accountInstructions.setBackground(getBackground());
		accountInstructions.setPreferredSize(new Dimension(400, 100));
		if (once == false) {
			mainPage.add(accountInstructions);
		}
		selectedAccount = new Account();
		this.add(mainPage);
		this.validate();
		this.repaint();
		once = true;

	}

	//////////////////////***** BEGINNING OF PANEL/TAB INITIALIZATIONS  ********** //////////////////////////////
	/**
	 * The heart of the GUI.  Creates the JTabbedPane and initializes all tabs/panels.  
	 */
	public void initPrimaryOptions() {
		//First creates the JPanel
		dayPortfolioPanel = new JPanel();
		currentPortfolioPanel = new JPanel();
		sellPanel = new JPanel();
		depositPanel = new JPanel();
		buyPanel = new JPanel();
		selectedAccountInfo = new JTextArea("    Selected Account: "
				+ selectedAccount.toString() + "\n\n");
		selectedAccountInfo.setEditable(false);
		selectedAccountInfo.setBackground(this.getBackground());
		customerPanel = new JPanel(new BorderLayout());
		customerPanel.add(selectedAccountInfo, BorderLayout.NORTH);
		JTabbedPane customerOptions = new JTabbedPane(SwingConstants.TOP,
				JTabbedPane.SCROLL_TAB_LAYOUT);
		customerPanel.setPreferredSize(new Dimension(this.getWidth(), 340));
		customerOptions.setPreferredSize(new Dimension(this.getWidth(), this
				.getHeight()));
		//Sets size of the JPanels
		buyPanel.setMaximumSize(new Dimension(this.getWidth(),
				this.getHeight() / 2));
		depositPanel.setMaximumSize(new Dimension(this.getWidth(), this
				.getHeight() / 2));
		sellPanel.setMaximumSize(new Dimension(this.getWidth(), this
				.getHeight() / 2));
		currentPortfolioPanel.setMaximumSize(new Dimension(this.getWidth(),
				this.getHeight() / 2));
		dayPortfolioPanel.setMaximumSize(new Dimension(this.getWidth() / 2,
				this.getHeight() / 3));
		customerOptions.addTab("Deposit", depositPanel);
		initDepositPanel(); //Initializes Deposit Panel
		customerOptions.addTab("Buy", buyPanel);
		initBuyPanel(); //Initializes Buy Panel
		customerOptions.addTab("Sell", sellPanel);
		customerOptions.addTab("Current Portfolio", currentPortfolioPanel);
		initSellPanel(); //Initializes Sell Panel
		initPortfolio(); //Initializes Portfolio Panel, which displays the current Portfolio of the selected account.
		initDayPortfolio(); //Initializes the DayPortfolio, which displays the selected accounts portfolio on any selected day.
		customerOptions.addTab("Transaction History", dayPortfolioPanel);
		customerPanel.add(customerOptions, BorderLayout.CENTER);
		JTextArea displayFeesCollected = new JTextArea("Total Fees Collected $"
				+ this.updateFeesCollected());
		displayFeesCollected.setEditable(false);
		displayFeesCollected.setBackground(getBackground());
		customerPanel.add(displayFeesCollected, BorderLayout.PAGE_END);
		this.add(customerPanel);
		this.revalidate();
		this.repaint();

	}
	
	/**
	 * Initializes the Deposit panel.  Like most of the other tabs, uses a single JPanel and then adds two sub-JPanels to the container panel for alignment purposes.
	 * Allows for deposit to be entered, and then passes the rest of the functionality to the actionPerformed method, which then calls submitDeposit();
	 */
	public void initDepositPanel() {
		depositPanel
				.setLayout(new BoxLayout(depositPanel, BoxLayout.PAGE_AXIS));
		currentBalanceText = new JTextArea("\nYour Current Balance is: $"
				+ selectedAccount.RoundTo2Decimals(selectedAccount
						.getOpeningBalance()) + ".  \nEnter "
				+ "amount you would like to deposit into your account.\n");
		currentBalanceText.setBackground(getBackground());
		JPanel allign2Panel = new JPanel();
		JPanel allignPanel = new JPanel();
		depositAmount = new JTextField();
		depositAmount.setPreferredSize(new Dimension(300, 30));
		JButton depositButton = new JButton("Deposit");
		depositButton.addActionListener(this);
		allignPanel.add(depositAmount);
		allignPanel.add(depositButton);
		allign2Panel.add(currentBalanceText);
		depositPanel.add(allign2Panel);
		depositPanel.add(allignPanel);
		currentBalanceText.setEditable(false);

	}
	
	/**
	 * Processes deposit, updates the selcted account, and then synchronizes the selected account with the overall AccountList, which is taken from Accounts.txt
	 */
	public void submitDeposit(){
		selectedAccount.setOpeningBalance(selectedAccount
				.RoundTo2Decimals(selectedAccount.getOpeningBalance())
				+ Double.parseDouble(depositAmount.getText()));
		double depositAmountDouble = Double.parseDouble(depositAmount
				.getText());
		depositAmount.setText("");
		currentBalanceText.setText("\nYour Current Balance is: $"
				+ selectedAccount.RoundTo2Decimals(selectedAccount
						.getOpeningBalance()) + ".  \nEnter "
				+ "amount you would like to deposit into your account.\n");
		this.updateSelectedAccount();
		selectedAccountInfo.setText("    Selected Account: "
				+ selectedAccount.toString() + "\n\n");
		allTransactionsList.add(new Transaction(selectedAccount
				.getCustomerID(), selectedAccount.getCustomerName(), today,
				"Deposit", depositAmountDouble));
		selectedAccount.getPortfolio().setAllTransactionsList(
				allTransactionsList);
		selectedAccount.getPortfolio().updatePortfolio();
		this.revalidate();
		this.repaint();
	}

	
	/**
	 * Initializes the Buy panel.  Takes the current stocks from the StockList vector (which is taken from the StockQuotes.txt), and then displays
	 * these stocks along with their corresponding price.  Passes on responsibility for processing the transaction to the actionListener, which then calls
	 * isValidBuy().  If isValidBuy returns true, the buy transaction is processed.
	 * 
	 * initBuyPanel --> actionListener --> if isValidBuy() == true --> Buy()
	 */
	public void initBuyPanel() {
		// Loads current Portfolio into an array
		buyPanel.setLayout(new BorderLayout());
		JButton buyShares = new JButton("Buy Shares");
		buyShares.addActionListener(this);
		Vector<Vector<String>> currentPortfolioArray = new Vector<Vector<String>>();
		System.out.println("Current Selected Account: "
				+ selectedAccount.getCustomerName());
		for (int x = 0; x <= stockList.size() - 1; x++) {

			Vector tempVector = new Vector();
			tempVector.add(stockList.get(x).getStockSymbol());
			tempVector.add(stockList.get(x).getStockPrice());
			currentPortfolioArray.add(tempVector);

		}

		Vector<Vector<String>> columnItems = new Vector<Vector<String>>();
		Vector tempVector = new Vector();
		tempVector.add("Stock Symbol");
		columnItems.add(tempVector);
		tempVector = new Vector();
		tempVector.add("Stock Price");
		columnItems.add(tempVector);

		JTable currentBuyTable = new JTable(currentPortfolioArray, columnItems);
		new JScrollPane(currentBuyTable);
		currentBuyTable.setFillsViewportHeight(true);

		listSelectionModel = currentBuyTable.getSelectionModel();
		listSelectionModel.addListSelectionListener(this);

		buyPanel.add(currentBuyTable.getTableHeader(), BorderLayout.PAGE_START);
		buyPanel.add(currentBuyTable, BorderLayout.CENTER);

		JPanel buyOptions = new JPanel();
		buyOptions.setPreferredSize(new Dimension(this.getWidth() / 3, this
				.getHeight() / 7));
		displaySelectedStock = new JTextArea("Stock: None Selected");
		displaySelectedStock.setBackground(getBackground());
		displaySelectedStock.setEditable(false);
		howManyShares = new JTextField("0");
		howManyShares.setBackground(Color.white);
		howManyShares.setPreferredSize(new Dimension(50, 30));
		JTextArea askHowManyShares = new JTextArea("     # of Shares:");
		askHowManyShares.setBackground(getBackground());
		buyOptions.add(displaySelectedStock);
		buyOptions.add(askHowManyShares);
		buyOptions.add(howManyShares);
		buyOptions.add(buyShares);
		buyPanel.add(buyOptions, BorderLayout.PAGE_END);

	}
	
	/**
	 * Determines if the selected account has the sufficient balance to purchase a given stock.
	 * @param quantity
	 * @param stockPrice
	 * @return
	 */
	public boolean isValidBuy(double quantity, double stockPrice) {
		return ((quantity * stockPrice) < selectedAccount.getOpeningBalance());
	}

	
	
	/**
	 * Processes the Buy transaction.  
	 * @param stockSymbol
	 * @param quantity
	 * @param day
	 */
	public void buy(String stockSymbol, double quantity, int day) {
		// get selected stock price
		System.out.println("DAY: " + day);
		double price = 0;
		for (int x = 0; x <= stockList.size() - 1; x++) {
			if (stockSymbol.equals(stockList.get(x).getStockSymbol())) {
				price = stockList.get(x).getStockPrice();
			}
		}
		selectedAccount.setOpeningBalance(selectedAccount.getOpeningBalance()
				- (quantity * price));
		JOptionPane.showMessageDialog(   //successful transaction confirmation
				this,
				"Purchase Complete.  Account ID "
						+ selectedAccount.getCustomerID()
						+ " has purchased "
						+ quantity
						+ " shares of "
						+ selectedStock
						+ ".  Balance is $"
						+ selectedAccount.RoundTo2Decimals(selectedAccount
								.getOpeningBalance()) + ".");

		// Adds transaction to transactionList
		allTransactionsList.add(new Transaction(
				selectedAccount.getCustomerID(), selectedAccount
						.getCustomerName(), day, "Buy", stockSymbol, quantity,
				price));
		selectedAccount.getPortfolio().setAllTransactionsList(
				allTransactionsList);
		selectedAccount.getPortfolio().updatePortfolio();
		this.remove(customerPanel);
		this.revalidate();
		this.repaint();
		chooseAccount();

	}

	
	/**
	 * Initializes the Sell Panel/Tab.  Stocks are displayed in a JTable, and there is a selectionListener which displays the selected stock option.
	 * Similar to Buy process, the Sell Panel is first initialized, then the actionListener will respond to a submit button being pressed and call the isvalidSell()
	 * function.  If isValidSell returns true, the Sell() function is called which processes the transaction.
	 * 
	 * In summary, the flow is initSellPanel() --> ActionListener --> isValidSell() --> Sell()
	 */
	public void initSellPanel() {

		// Loads current Portfolio into an array
		sellPanel.setLayout(new BorderLayout());
		JButton sellShares = new JButton("Sell Shares");
		sellShares.addActionListener(this);
		Vector<Vector<String>> currentPortfolioArray = new Vector<Vector<String>>();
		System.out.println("Current Selected Account: "
				+ selectedAccount.getCustomerName());
		for (int x = 0; x <= stockList.size() - 1; x++) {

			Vector tempVector = new Vector();
			tempVector.add(stockList.get(x).getStockSymbol());
			tempVector.add(selectedAccount.getPortfolio().getNumberOfShares()
					.get(x));
			tempVector.add(stockList.get(x).getStockPrice());
			currentPortfolioArray.add(tempVector);

		}

		Vector<Vector<String>> columnItems = new Vector<Vector<String>>();
		Vector tempVector = new Vector();
		tempVector.add("Stock Symbol");
		columnItems.add(tempVector);
		tempVector = new Vector();
		tempVector.add("Number of Shares");
		columnItems.add(tempVector);
		tempVector = new Vector();
		tempVector.add("Stock Price");
		columnItems.add(tempVector);

		JTable currentSellTable = new JTable(currentPortfolioArray, columnItems);
		new JScrollPane(currentSellTable);
		currentSellTable.setFillsViewportHeight(true);

		listSelectionModel2 = currentSellTable.getSelectionModel();
		listSelectionModel2.addListSelectionListener(this);

		sellPanel.add(currentSellTable.getTableHeader(),
				BorderLayout.PAGE_START);
		sellPanel.add(currentSellTable, BorderLayout.CENTER);

		JPanel sellOptions = new JPanel();
		sellOptions.setPreferredSize(new Dimension(this.getWidth() / 3, this
				.getHeight() / 7));
		displaySelectedStock2 = new JTextArea("Stock: None Selected");
		displaySelectedStock2.setBackground(getBackground());
		displaySelectedStock2.setEditable(false);
		howManyShares2 = new JTextField();
		howManyShares2.setPreferredSize(new Dimension(50, 30));
		JTextArea askHowManyShares = new JTextArea("     # of Shares:");
		askHowManyShares.setBackground(getBackground());
		sellOptions.add(displaySelectedStock2);
		sellOptions.add(askHowManyShares);
		sellOptions.add(howManyShares2);
		sellOptions.add(sellShares);
		sellPanel.add(sellOptions, BorderLayout.PAGE_END);

	}
	
	/**
	 * Identifies if the user has the stock for which the user wants to sell.  If so, returns true, if not returns false.
	 * @param stockSymbol
	 * @param quantity
	 * @return
	 */
	public boolean isValidSell(String stockSymbol, double quantity) {

		for (int x = 0; x <= stockList.size() - 1; x++) {
			if (stockSymbol.equals(stockList.get(x).getStockSymbol())) {
				if (selectedAccount.getPortfolio().getNumberOfShares().get(x) >= quantity) {

					return true;
				}
			}
		}

		return false;
	}
	

	/**
	 * Processes a sell transaction.  This method is only called if the isValidSell() returns true.
	 * 
	 * Removes shares from SelectedAccounts portfolio, and adds $ to balance.  Synchronizes the selected  account with the overall AccountList.
	 */
	public void sell() {

		double tempDoublePrice = 0.0;
		for (int x = 0; x <= stockList.size() - 1; x++) {
			if (stockList.get(x).getStockSymbol().equals(stockToSell)) {
				tempDoublePrice = stockList.get(x).getStockPrice();
			}
		}
		if (isValidSell(stockToSell,
				Double.parseDouble(howManyShares2.getText())) == true) {
			Transaction tempSellTransaction = new Transaction(
					selectedAccount.getCustomerID(),
					selectedAccount.getCustomerName(), today, "Sell",
					stockToSell, Double.parseDouble(howManyShares2.getText()),
					tempDoublePrice);
			allTransactionsList.add(tempSellTransaction);
			selectedAccount.getPortfolio().setAllTransactionsList(
					allTransactionsList);
			selectedAccount.setOpeningBalance(selectedAccount
					.RoundTo2Decimals(selectedAccount.getOpeningBalance())
					+ (tempDoublePrice * Double.parseDouble(howManyShares2
							.getText())));
			this.updateSelectedAccount();
			JOptionPane.showMessageDialog(
					this,
					"Successfull Transaction!  Your new account balance is $"
							+ selectedAccount.RoundTo2Decimals(selectedAccount
									.getOpeningBalance()));
			this.remove(customerPanel);
			this.revalidate();
			this.repaint();
			selectedAccount = null;
			mainPage.remove(accountInstructions);

			chooseAccount();

		} else {

			JOptionPane
					.showMessageDialog(this,
							"Invalid transaction.  You do not have enough shares to make this transaction.");

		}

	}

	
	/**
	 * Initializes and displays current portfolio (the shares the account owns and the price of these shares) in a JTable.
	 * 
	 * This information is retrieved the associated Portfolio object of the Selected Account.  Each Account has an associated Portfolio object which
	 * includes functionality to display the Portfolio of an Account by iterating through the Transactions.txt file and calculates how many shares and how much $
	 * the selected account has.
	 */
	public void initPortfolio() {

		// Loads current Portfolio into an array
		currentPortfolioPanel.setLayout(new BorderLayout());
		Vector<Vector<String>> currentPortfolioArray = new Vector<Vector<String>>();
		System.out.println("Current Selected Account: "
				+ selectedAccount.getCustomerName());
		for (int x = 0; x <= stockList.size() - 1; x++) {
			if (selectedAccount.getPortfolio().getNumberOfShares().get(x) != 0.0) {
				Vector tempVector = new Vector();
				tempVector.add(stockList.get(x).getStockSymbol());
				tempVector.add(selectedAccount.getPortfolio()
						.getNumberOfShares().get(x));
				tempVector.add(stockList.get(x).getStockPrice());
				currentPortfolioArray.add(tempVector);
			}
		}

		Vector<Vector<String>> columnItems = new Vector<Vector<String>>();
		Vector tempVector = new Vector();
		tempVector.add("Stock Symbol");
		columnItems.add(tempVector);
		tempVector = new Vector();
		tempVector.add("Number of Shares");
		columnItems.add(tempVector);
		tempVector = new Vector();
		tempVector.add("Stock Price");
		columnItems.add(tempVector);
		JTextArea displayTotalValue = new JTextArea(
				"Current Total Stock Value: $"
						+ this.RoundTo2Decimals(getStockValue(today)));
		displayTotalValue.setBackground(this.getBackground());
		JTable currentPortfolioTable = new JTable(currentPortfolioArray,
				columnItems);
		new JScrollPane(currentPortfolioTable);
		currentPortfolioTable.setFillsViewportHeight(true);

		//Displays portfolio in allignment 
		currentPortfolioPanel.add(currentPortfolioTable.getTableHeader(),
				BorderLayout.PAGE_START);
		currentPortfolioPanel.add(currentPortfolioTable, BorderLayout.CENTER);
		currentPortfolioPanel.add(displayTotalValue, BorderLayout.PAGE_END);
	}



	/**
	 * Initially displays a list of the days in which the brokerage has been alive since.  Then allows the user to press the "Load History" button
	 * to see what the selected accounts portfolio was on that given day.  The actionListener then responds to the pressing of the "Load History"
	 * button, which calls displayPortfolioHistory(), which is the method that actually fills the history.
	 * 
	 * Flow for displayiing portfolio on a given day is initDayPortfolio() --> actionPerformed --> displayPortfolioHistory()
	 */
	public void initDayPortfolio() {
		dayPortfolioPanel.setMaximumSize(new Dimension(this.getWidth() / 2,
				this.getHeight() / 2));
		currentStockValue = new JTextArea("Total Stock Value: ");
		currentStockValue.setEditable(false);
		currentStockValue.setBackground(this.getBackground());
		currentCashValue = new JTextArea("Balance as of Day:");
		currentCashValue.setEditable(false);
		currentCashValue.setBackground(this.getBackground());
		JPanel tempPanel = new JPanel();
		tempPanel.setPreferredSize(new Dimension(this.getWidth() / 3, this
				.getHeight() / 7));
		dayPortfolioPanel.setLayout(new BoxLayout(dayPortfolioPanel,
				BoxLayout.PAGE_AXIS));
		Vector<Integer> allDays = new Vector();
		JButton loadDayButton = new JButton("Load History");
		loadDayButton.addActionListener(this);
		// Create the combo box, select item at index 4.
		// Indices start at 0, so 4 specifies the pig.
		JTextArea displayInstructions = new JTextArea(
				"Choose Day to View Portfolio History");
		displayInstructions.setBackground(this.getBackground());
		displayInstructions.setEditable(false);
		for (int x = 0; x <= today - 1; x++) {
			allDays.add(x, x + 1);
		}

		allDaysBox = new JComboBox<Integer>(allDays);
		tempPanel.add(displayInstructions);
		tempPanel.add(allDaysBox);
		tempPanel.add(loadDayButton);
		tempPanel.add(currentStockValue);
		tempPanel.add(currentCashValue);
		dayPortfolioPanel.add(tempPanel);
		this.validate();
		this.repaint();
	}
	
	
	/**
	 * Obtains portfolio information from the associated Portfolio object of the selected account.  Displays history in a JTable, along with the balance and
	 * total stock value of the account on that day.
	 */
	public void displayPortfolioHistory() {
		//Fixes visual glitch
		if (clearTable == true) {
			dayPortfolioPanel.remove(currentPortfolioTable);
		}

		// Loads current Portfolio into a Vector
		Vector<Vector<String>> currentPortfolioArray = new Vector<Vector<String>>();
		int day = (int) allDaysBox.getSelectedItem(); //Identifies day that the user wants to go back to and display history of.
		selectedAccount.getPortfolio().getSharesUpToDate(day);
		for (int x = 0; x <= stockList.size() - 1; x++) {
			if (selectedAccount.getPortfolio().getSharesThroughDate()
					.get(x) > 0) {
				Vector tempVector = new Vector();
				tempVector.add(stockList.get(x).getStockSymbol());
				tempVector.add(selectedAccount.getPortfolio()
						.getSharesThroughDate().get(x));
				tempVector.add(Stock.getStockValue(stockList.get(x)
						.getStockSymbol(), day));
				currentPortfolioArray.add(tempVector);
			}
		}

		// Calculates balance on specified day by going through transactions list and adding and subtracting $ based on the type of transaction (buy, sell, deposit)
		double cashOnDay = 0;
		for (int x = 0; x <= allTransactionsList.size() - 1; x++) {
			if (allTransactionsList.get(x).getTransactionType()
					.equals("Deposit")
					&& allTransactionsList.get(x).getCustomerID() == selectedAccount
							.getCustomerID()
					&& allTransactionsList.get(x).getTransactionDate() <= day) {
				cashOnDay = cashOnDay
						+ allTransactionsList.get(x).getPrice();
			}
			if (allTransactionsList.get(x).getTransactionType()
					.equals("Buy")
					&& allTransactionsList.get(x).getCustomerID() == selectedAccount
							.getCustomerID()
					&& allTransactionsList.get(x).getTransactionDate() <= day) {
				cashOnDay = cashOnDay
						- (allTransactionsList.get(x).getPrice() * allTransactionsList
								.get(x).getQuantity());
			}
			if (allTransactionsList.get(x).getTransactionType()
					.equals("Sell")
					&& allTransactionsList.get(x).getCustomerID() == selectedAccount
							.getCustomerID()
					&& allTransactionsList.get(x).getTransactionDate() <= day) {
				cashOnDay = cashOnDay
						+ (allTransactionsList.get(x).getPrice() * allTransactionsList
								.get(x).getQuantity());
			}

		}
		
		currentCashValue.setText("Balance as of Day " + day + ": $"  //Displays balance as of the given day.
				+ cashOnDay);

		//Loads values into JTable
		Vector<Vector<String>> columnItems = new Vector<Vector<String>>();
		Vector tempVector = new Vector();
		tempVector.add("Stock Symbol");
		columnItems.add(tempVector);
		tempVector = new Vector();
		tempVector.add("Number of Shares");
		columnItems.add(tempVector);
		tempVector = new Vector();
		tempVector.add("Stock Price On Specified Day");
		columnItems.add(tempVector);
		currentStockValue.setText("Total Stock Value: $"
				+ this.RoundTo2Decimals(getStockValue(day)));
		currentPortfolioTable = new JTable(currentPortfolioArray,
				columnItems);
		scrollpane = new JScrollPane(currentPortfolioTable);
		currentPortfolioTable.setFillsViewportHeight(true);

		if (clearTable != true) {
			dayPortfolioPanel.add(currentPortfolioTable.getTableHeader(),
					BorderLayout.PAGE_START);
		}

		dayPortfolioPanel.add(currentPortfolioTable, BorderLayout.CENTER);
		clearTable = true;
		validate();
		repaint();
	}

	


	/**
	 * Returns the total amount of stock value in the selected account on a given day.  Obtained by multiplying
	 * the shares the account had on the given day by the price of the shares on that given day.  If no information is found 
	 * for the price of those shares on the specified day, then the function uses the price of the shares from the closest
	 * day for which there is available information.
	 * 
	 * 
	 * @param day
	 * @return
	 */
	public double getStockValue(int day) {
		Double totalStockValue = 0.0;
		Vector<Vector<String>> currentPortfolioArray = new Vector<Vector<String>>();
		selectedAccount.getPortfolio().getSharesUpToDate(day);
		for (int x = 0; x <= stockList.size() - 1; x++) {
			if (selectedAccount.getPortfolio().getSharesThroughDate().get(x) > 0) {
				Vector tempVector = new Vector();
				tempVector.add(stockList.get(x).getStockSymbol());
				tempVector.add(selectedAccount.getPortfolio()
						.getSharesThroughDate().get(x));
				totalStockValue = totalStockValue
						+ (selectedAccount.getPortfolio()
								.getSharesThroughDate().get(x) * Stock
								.getStockValue(stockList.get(x)
										.getStockSymbol(), day));
				tempVector.add(Stock.getStockValue(stockList.get(x)
						.getStockSymbol(), day));
				currentPortfolioArray.add(tempVector);
			}
		}

		return totalStockValue;
	}

	
	

	
	/**
	 * THis is the create account panel.  Takes in user information and creates new account.  Returns to the Choose Account panel after completion
	 */
	public void initCreateAccountPanel() {

		this.revalidate();
		this.repaint();
		createAccountPanel = new JPanel();
		createAccountPanel.setLayout(new GridLayout(5, 5));
		instructions = new JTextArea("Please enter account information...");
		instructions.setBackground(this.getBackground());
		filler = new JTextArea(" ");
		filler.setBackground(this.getBackground());
		nameInstruction = new JTextArea("Name: ");
		nameInstruction.setBackground(this.getBackground());
		nameInstruction.setEditable(false);
		name = new JTextField();
		enterDate = new JTextArea("Date: ");
		enterDate.setBackground(this.getBackground());
		enterDate.setEditable(false);
		date = new JTextField();
		enterBalance = new JTextArea("Enter Balance:");
		enterBalance.setBackground(this.getBackground());
		enterBalance.setEditable(false);
		balance = new JTextField();
		submitAccount = new JButton("Create Account");
		submitAccount.addActionListener(this);

		createAccountPanel.add(instructions);
		createAccountPanel.add(filler);
		createAccountPanel.add(nameInstruction);
		createAccountPanel.add(name);
		createAccountPanel.add(enterDate);
		createAccountPanel.add(date);
		createAccountPanel.add(enterBalance);
		createAccountPanel.add(balance);
		createAccountPanel.add(submitAccount);
		createAccountPanel.setVisible(true);
		this.add(createAccountPanel);
		this.revalidate();
		this.repaint();

	}

	
/**
 * Displays the amount of fees collected for the Brokerage Firm on a single day.  This function displays the panel and
 * waits for the user to select a day.  Once the user selects a day, the actionPerformed method handles the event and passes onto
 * calculateFeeRevenue() which performs the calculations.
 */
	public void initFeesByDayPanel() {
		
		feesByDayPanel = new JPanel(new BorderLayout());
		feesByDayPanel.setPreferredSize(new Dimension(this.getWidth()/2,this.getHeight()/4));
		feesByDayPanel2 = new JPanel(new BorderLayout());
		feesByDayPanel2.setPreferredSize(new Dimension(this.getWidth()/2,this.getHeight()/2));
		JTextArea feesInstructions = new JTextArea("Select a day and then press calculate fees.");
		JButton FeeRevenueByDayButton = new JButton("Calculate Fee Revenue");
		FeeRevenueByDayButton.addActionListener(this);
		feesInstructions.setEditable(false);
		feesInstructions.setBackground(getBackground());
		
		Vector<Integer> allDays2 = new Vector<Integer>();
		for (int x = 0; x <= today - 1; x++) {
			allDays2.add(x, x + 1);
		}

		allDaysBox2 = new JComboBox<Integer>(allDays2);	
		feesByDayPanel.add(feesInstructions, BorderLayout.PAGE_START);
		feesByDayPanel.add(allDaysBox2, BorderLayout.CENTER);
		feesByDayPanel.add(FeeRevenueByDayButton, BorderLayout.PAGE_END);
		displayFeesByDay = new JTextArea("Fees Collected: $0");
		displayFeesByDay.setBackground(this.getBackground());
		feesByDayPanel2.add(displayFeesByDay);
		feesByDayIsOpen = true;

		this.add(feesByDayPanel);
		this.add(feesByDayPanel2);
		this.validate();
		this.repaint();
	}
	
	
	/**
	 * Calculates the amount of fees collected by the firm on a single day.  The calculation is done by iterating through
	 * the transactionsList and adding $10 to the fee revenue for that day for each Buy and Sell transaction.
	 */
	public void calculateFeeRevenue(){
		int day3 = (int)allDaysBox2.getSelectedItem();
		int totalFees = 0;
		for(int x = 0; x<=allTransactionsList.size()-1; x++){
			if((allTransactionsList.get(x).getTransactionType().equals("Sell") || allTransactionsList.get(x).getTransactionType().equals("Buy")) && allTransactionsList.get(x).getTransactionDate() == day3){
				totalFees = totalFees + 10;
			}
		}
		displayFeesByDay.setText("Fees Collected: $" + totalFees);
	
	}
	
	/**
	 * Simply iterates through the accounts and prints their information.  Used mainly for debugging purposes.
	 */
	public void printAccounts() {
		for (int x = 0; x <= accountList.size() - 1; x++) {
			System.out.println(accountList.get(x).toString());
		}
	}

	/**
	 * Convenient auxiliary method which takes in a double and displays that double in a readable ###.## form.
	 * @param val
	 * @return
	 */
	public double RoundTo2Decimals(double val) {
		DecimalFormat df2 = new DecimalFormat("###.##");
		return Double.valueOf(df2.format(val));
	}

	

	/**
	 * Calculates the revenue from Transaction Fees for all transactions to ever take place in firm.
	 */
	public int updateFeesCollected() {
		feeRevenue = 0;
		for (int x = 0; x <= allTransactionsList.size() - 1; x++) {
			if (allTransactionsList.get(x).getTransactionType().equals("Buy")
					|| allTransactionsList.get(x).getTransactionType()
							.equals("Sell")) {
				feeRevenue = feeRevenue + 10;
			}

		}
		return feeRevenue;

	}

	/**
	 * Synchronizes the selected account being edited with the overall Vector of
	 * Accounts
	 */
	public void updateSelectedAccount() {
		int x;
		for (x = 0; x <= accountList.size() - 1; x++) {
			if (accountList.get(x).getCustomerID() == selectedAccount
					.getCustomerID()) {
				accountList.set(x, selectedAccount);
			}
		}
	}
	
	
	
	
	
	
	/////////////////////****************************************\\\\\\\\\\\\\\\\\\\\\\\\\\\\
	/**
	 * Beginning of Action Performed Methods
	 * 
	 * 
	 * The vast majority of these if statements read in or write to text files, or they simply call another method to take care of the event.
	 * 
	 * 
	 * 
	 */
	
	@Override
	public void actionPerformed(ActionEvent e) {

		if (e.getActionCommand().equals("Load Accounts")) {
			if(feesByDayIsOpen == true){
			this.remove(this.feesByDayPanel);
			this.remove(this.feesByDayPanel2);
				this.add(mainPage);
				chooseAccount.updateUI();
				this.validate();
				this.repaint();
				feesByDayIsOpen = false;
			}
			
			JFileChooser fileOpener = new JFileChooser("/");
			int returnVal = fileOpener.showOpenDialog(getParent());

			if (returnVal == JFileChooser.APPROVE_OPTION) {
				accountsFile = fileOpener.getSelectedFile();
			} else {
				System.out.println("You have not selected a file.");
			}

			// Retrieves accounts text file
			in = null;
			String singleAccount = null;
			try {
				in = new BufferedReader(new FileReader(accountsFile));
			} catch (FileNotFoundException err) {
				System.out.println(err.getMessage());
			}

			// Adds accounts from text files to AccountsList and displays them
			// in JComboBox
			singleAccount = null;
			accountList.clear();
			try {
				while ((singleAccount = in.readLine()) != null) {
					Account tempAccount = new Account();
					tempAccount.setCustomerID(Integer.parseInt(singleAccount
							.split(",")[0]));
					tempAccount.setCustomerName(singleAccount.split(",")[1]);
					tempAccount.setOpeningDate(Integer.parseInt(singleAccount
							.split(",")[2]));
					tempAccount.setOpeningBalance(Double
							.parseDouble(singleAccount.split(",")[3]));
					accountList.add(tempAccount);
				}
				in.close();
			} catch (IOException err) {
				System.out.println(err.getMessage());
			}

			// Loads transactions File into transactionList Vector
			transactionsFile = new File("Transactions.txt");
			try {
				in = new BufferedReader(new FileReader(transactionsFile));
			} catch (FileNotFoundException err) {
				System.out.println(err.getMessage());
			}
			String singleTransaction = null;
			allTransactionsList.clear();
			try {
				while ((singleTransaction = in.readLine()) != null) {
					Transaction tempTransaction = new Transaction();
					tempTransaction.setCustomerID(Integer
							.parseInt(singleTransaction.split(",")[0]));
					tempTransaction.setCustomerName(singleTransaction
							.split(",")[1]);
					tempTransaction.setTransactionDate(Integer
							.parseInt(singleTransaction.split(",")[2]));
					tempTransaction.setTransactionType(singleTransaction
							.split(",")[3]);
					tempTransaction
							.setStockSymbol(singleTransaction.split(",")[4]);
					tempTransaction.setQuantity(Double
							.parseDouble(singleTransaction.split(",")[5]));
					tempTransaction.setPrice(Double
							.parseDouble(singleTransaction.split(",")[6]));
					allTransactionsList.add(tempTransaction);
				}
				in.close();
			} catch (IOException err) {
				System.out.println(err.getMessage());
			}

			// Loads the stockHistory from data file to the allStockHistory
			// Vector
			try {
				BufferedReader in = new BufferedReader(new FileReader(
						"StockHistory.txt"));
				String tempStockHistory;
				allStockHistory.clear();

				while ((tempStockHistory = in.readLine()) != null) {
					allStockHistory.add(tempStockHistory);
				}
				in.close();
			} catch (Exception e4) {
				System.out.println(e4.getMessage());
			}

			// Greys out options if user hasn't loaded a data file yet. There
			// must be a data file.
			if (mainPageCached == false) {
				chooseAccount = new JComboBox<Account>(accountList);
				chooseAccount.setPreferredSize(new Dimension(this.getWidth(),
						this.getHeight()));
				mainPage.add(chooseAccount);
				JButton enterAccount = new JButton("Access Account");
				enterAccount.addActionListener(this);
				mainPage.add(enterAccount);
				newAcct.setEnabled(true);
				saveAs.setEnabled(true);
				save.setEnabled(true);
				feesByDayButton.setEnabled(true);
				this.validate();
				mainPageCached = true;
			} else {
				this.remove(customerPanel);
				this.add(mainPage);
				chooseAccount.updateUI();
				this.revalidate();
				this.repaint();
			}

		}

		// Access account button pressed and primary broker options are
		// displayed
		if (e.getActionCommand().equals("Access Account")) {
			this.remove(mainPage);
			this.remove(customerPanel);
			selectedAccount = (Account) chooseAccount.getSelectedItem();
			System.out.println(selectedAccount.toString());
			selectedAccount.getPortfolio().setAllTransactionsList(
					allTransactionsList);
			selectedAccount.getPortfolio().updatePortfolio();
			this.initPrimaryOptions();

		}

		// Create new account chosen from File menu, initiates the Add Account
		// options
		if (e.getActionCommand().equals("Create New Account")) {
			this.remove(customerPanel);
			this.remove(mainPage);
			repaint();
			revalidate();
			initCreateAccountPanel();
		}

		// Add Account form submitted, so the information is added to the
		// accountList vector. NEED TO DO VALIDATION CHECKING
		if (e.getActionCommand().equals("Create Account")) {
			Account tempAccount = new Account();
			tempAccount.setCustomerName(name.getText());
			tempAccount.setOpeningDate(Integer.parseInt(date.getText()));
			tempAccount
					.setOpeningBalance(Double.parseDouble(balance.getText()));
			tempAccount.setCustomerID(accountList.get(accountList.size() - 1)
					.getCustomerID() + 1);

			try {
				out = new BufferedWriter(new FileWriter(accountsFile, true));
				out.newLine();
				out.write(tempAccount.getCustomerID() + ","
						+ tempAccount.getCustomerName() + ","
						+ tempAccount.getOpeningDate() + ","
						+ tempAccount.getOpeningBalance());
				out.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				System.out.println(e1.getMessage());
			}

			accountList.add(tempAccount);
			chooseAccount.updateUI();
			this.remove(createAccountPanel);
			this.add(mainPage);
			chooseAccount.updateUI();
			this.validate();
			this.repaint();
		}

		// Saves accountList to file picked out by user
		if (e.getActionCommand().equals("Save As")) {
			BufferedWriter out2 = null;
			JFileChooser fileSaver = new JFileChooser();
			int returnVal = fileSaver.showSaveDialog(getParent());

			if (returnVal == JFileChooser.APPROVE_OPTION) {
				savedFile = fileSaver.getSelectedFile();
			} else {
				System.out.println("You have not selected a file.");
			}

			try {
				out2 = new BufferedWriter(new FileWriter(savedFile, true));
				for (int x = 0; x <= accountList.size() - 1; x++) {
					if (x > 0) {
						out2.newLine();
					}
					out2.write(accountList.get(x).getCustomerID() + ","
							+ accountList.get(x).getCustomerName() + ","
							+ accountList.get(x).getOpeningDate() + ","
							+ accountList.get(x).getOpeningBalance());
				}
				out2.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				System.out.println(e1.getMessage());
			}

			// Save all transactions to transactions file
			try {
				out2 = new BufferedWriter(
						new FileWriter(transactionsFile, true));
				for (int x = 0; x <= allTransactionsList.size() - 1; x++) {
					if (x > 0) {
						out2.newLine();
					}
					out2.write(allTransactionsList.get(x).getCustomerID() + ","
							+ allTransactionsList.get(x).getCustomerName()
							+ ","
							+ allTransactionsList.get(x).getTransactionDate()
							+ ","
							+ allTransactionsList.get(x).getTransactionType()
							+ "," + allTransactionsList.get(x).getStockSymbol()
							+ "," + allTransactionsList.get(x).getQuantity()
							+ "," + allTransactionsList.get(x).getPrice());
				}
				out2.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				System.out.println(e1.getMessage());
			}
			selectedAccount.getPortfolio().setAllTransactionsList(
					allTransactionsList);
			selectedAccount.getPortfolio().updatePortfolio();
			// Moves stockLists to stockHistory
			for (int x = 0; x <= stockList.size() - 1; x++) {
				allStockHistory.add(stockList.get(x).getStockSymbol() + ","
						+ today + "," + stockList.get(x).getStockPrice());
			}

			// Save stocks to StocksHistory data file NEED TO FINISH
			try {
				BufferedWriter out3 = new BufferedWriter(new FileWriter(
						"StockHistory.txt", true));
				for (int x = 0; x <= allStockHistory.size() - 1; x++) {
					out3.newLine();
					out3.write(allStockHistory.get(x));
				}
				out3.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());
			}
		}

		if (e.getActionCommand().equals("Sell Shares")) {
			this.sell();
		}

		if (e.getActionCommand().equals("Save")) {
			BufferedWriter out3 = null;
			try {
				out3 = new BufferedWriter(new FileWriter(accountsFile));
				for (int x = 0; x <= accountList.size() - 1; x++) {
					if (x > 0) {
						out3.newLine();
					}
					out3.write(accountList.get(x).getCustomerID() + ","
							+ accountList.get(x).getCustomerName() + ","
							+ accountList.get(x).getOpeningDate() + ","
							+ accountList.get(x).getOpeningBalance());
				}
				out3.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				System.out.println(e1.getMessage());
			}

			// Save all transactions to transactions file
			try {
				out3 = new BufferedWriter(new FileWriter(transactionsFile));
				for (int x = 0; x <= allTransactionsList.size() - 1; x++) {
					if (x > 0) {
						out3.newLine();
					}
					out3.write(allTransactionsList.get(x).getCustomerID() + ","
							+ allTransactionsList.get(x).getCustomerName()
							+ ","
							+ allTransactionsList.get(x).getTransactionDate()
							+ ","
							+ allTransactionsList.get(x).getTransactionType()
							+ "," + allTransactionsList.get(x).getStockSymbol()
							+ "," + allTransactionsList.get(x).getQuantity()
							+ "," + allTransactionsList.get(x).getPrice());
				}
				out3.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				System.out.println(e1.getMessage());
			}
			selectedAccount.getPortfolio().setAllTransactionsList(
					allTransactionsList);
			selectedAccount.getPortfolio().updatePortfolio();

			// Transfer current stockList to stockHistory
			for (int x = 0; x <= stockList.size() - 1; x++) {
				allStockHistory.add(stockList.get(x).getStockSymbol() + ","
						+ today + "," + stockList.get(x).getStockPrice());
			}

			try {
				out3 = new BufferedWriter(new FileWriter("StockHistory.txt",
						true));
				for (int x = 0; x <= allStockHistory.size() - 1; x++) {
					if (x > 0) {
						out3.newLine();
					}
					out3.write(allStockHistory.get(x));
				}
				out3.close();
			} catch (Exception e2) {
				System.out.println(e2.getMessage());
			}

		}
		
		if(e.getActionCommand().equals("View Fee Revenue By Day")){
			this.remove(customerPanel);
			this.remove(mainPage);
			repaint();
			revalidate();
			this.initFeesByDayPanel();
		}

		if (e.getActionCommand().equals("Deposit")) {
			submitDeposit();

		}

		if (e.getActionCommand().equals("Buy Shares")) {
			double howManyShares2 = Double.parseDouble(this.howManyShares
					.getText());
			System.out.println(howManyShares2);
			double selectedStockPrice = 0;
			// finds selected stock price
			for (int x = 0; x <= stockList.size() - 1; x++) {
				if (stockList.get(x).getStockSymbol().equals(selectedStock)) {
					selectedStockPrice = stockList.get(x).getStockPrice();
					System.out.println("Price: " + selectedStockPrice);
				}
			}

			// check if it is a validbuy
			if (isValidBuy(howManyShares2, selectedStockPrice) == true) {
				// find current date
				buy(selectedStock, howManyShares2, today);
				System.out.println("VALID BUY");
			} else {
				JOptionPane.showMessageDialog(this, "Account ID "
						+ selectedAccount.getCustomerID()
						+ " does not have sufficient funds to purchase "
						+ howManyShares2 + " shares of " + selectedStock);
			}

		}

		if (e.getActionCommand().equals("Load History")) {
			displayPortfolioHistory();


		}
		
		if(e.getActionCommand().equals("Quit")){
			System.exit(0);
		}
		
		if(e.getActionCommand().equals("Calculate Fee Revenue")){
			calculateFeeRevenue();
		}
	}


	@Override
	public void valueChanged(ListSelectionEvent e) {

		if (e.getSource().equals(listSelectionModel)) {

			selectedStock = stockList.get(e.getLastIndex()).getStockSymbol();
			System.out.println(selectedStock);
			displaySelectedStock.setText("Stock: " + selectedStock);

		}

		if (e.getSource().equals(listSelectionModel2)) {

			System.out.println(selectedStock2);
			selectedStock2 = stockList.get(e.getLastIndex()).getStockSymbol();
			stockToSell = selectedStock2;
			displaySelectedStock2.setText("Stock: " + selectedStock2);
		}

	}

}
